var datatable;// 定义一个全局的dataTable
var d;
var exportColumns;//导出的列
var paras;//查询条件
var columns;
$(function() {
	initTimeSize();
	initSelectRadio();
	isGoing();
	hideOrShow();
	//新加的
	var sp = $("#sp").val();
	 loadSite(sp);
	 $("#sp").combobox({
		select : function(event, ui) {
			loadSite();
		},
		width : 100
	 });
	
	
	$('#table tbody').on('click', 'tr', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
		} else {
			datatable.$('tr.selected').removeClass('selected');
			$(this).addClass('selected');
		}
	});

	$("#area").combobox();
	showArearList("area");
	
	$("#groupId").combobox();
	$("#terminalBrandId").combobox({
		select:function(event,ui){
			loadTerminalModel();
		}
	});
	$("#terminalModelId").combobox();  
	$("#apnId").combobox();
	$("#sgw").combobox();
	$("#area").combobox();
	//showArearList("area");
})

//是否选择  服务IP 展示的 查询维度
function hideOrShow(){
	
		var ipBoxValue=  $("input[name='serverIPBox']").is(':checked');
		if(ipBoxValue == true){
			$("#selectedvalue_5").attr("disabled","disabled");
			$('#selectedvalue_0').attr("disabled","disabled"); 
			$('#selectedvalue_1').attr("disabled","disabled"); 
			$('#selectedvalue_2').attr("disabled","disabled"); 
			$('#selectedvalue_3').attr("disabled","disabled"); 
		}else {
			//$('#selectedvalue_5').removeAttr("disabled"); 
			//$('#selectedvalue_5').attr("disabled",""); 
			$("#selectedvalue_5").attr("disabled", false);
			$('#selectedvalue_0').attr("disabled",false); 
			$('#selectedvalue_1').attr("disabled",false); 
			$('#selectedvalue_2').attr("disabled",false); 
			$('#selectedvalue_3').attr("disabled",false); 
		}
}



/**
 * 新加   SP  site
 * 
 * 
 */

function loadSite(sp) {
	var sp = $("#sp").val();
	$.ajax({
				url : '../../feature/sp/getSiteInfos?sp='
					+ sp,
				type : 'POST',
				dataType : 'JSON',
				error : function() {
					alert('Error loading data!');
				},
				success : function(msg) {
					$("#site").remove();
					$("#site").empty();
					$("#siteTD")
							.append(
									$("<select id='site' name='site'></select>"));
					$("#site").combobox();
					$("#site").append("<option value=''>全部</option>");
					var list = msg.siteList;
					$.each(eval(list), function(i, item) {
						$(
								"<option value='" + item.site + "'>"
										+ item.site + "</option>")
								.appendTo($("#site"));
					});
				}
			});
}


/**
 * 根据终端类型，加载终端型号
 * 
 * @param parentid
 */
function loadTerminalModel() {
	var terminalBrand = $("#terminalBrandId").val();
	
	$.ajax({
		url : '../../feature/terminalUE/terminalModelInfos?terminalBrand='
				+ terminalBrand,
		type : 'POST',
		dataType : 'JSON',
		error : function() {
			alert('Error loading data!');
		},
		success : function(msg) {
			$("#terminalModelId").remove();
			$("#terminalModelTD").append($("<select id='terminalModelId' name='terminalModelId'></select>"));
			$("#terminalModelId").combobox();
			$("#terminalModelId").append("<option value=''>全部</option>");
			var list = msg.terminalModelList;
			var terminalModelSelected =  $("#terminalModelSelected").val();
			if(terminalModelSelected){
				$.each(eval(list), function(i, item) {
					if(terminalModelSelected==item.terminal_model){
						$(
								"<option selected='selected' value='" + item.terminal_model + "'>"
								+ item.terminal_model + "</option>")
								.appendTo($("#terminalModelId"));
					}else{
						$(
								"<option value='" + item.terminal_model + "'>"
								+ item.terminal_model + "</option>")
								.appendTo($("#terminalModelId"));
					}
				});

			}else{
				
				$.each(eval(list), function(i, item) {
					$(
							"<option value='" + item.terminal_model + "'>"
							+ item.terminal_model + "</option>")
							.appendTo($("#terminalModelId"));
				});
			}
			
		}
	});
	
}

function isGoing(){
	var callId = $("#callId").val();
	if(!callId){
		var tacCheck = $("#tacCheck").val();
		var enodebidCheck = $("#enodebidCheck").val();
		var cellIdCheck = $("#cellIdCheck").val();
		if(tacCheck){
			$("#tacBox").attr("checked",true);
		}
		if(enodebidCheck){
			$("#eNodeBIDBox").attr("checked",true);
		}
		if(cellIdCheck){
			$("#cellBox").attr("checked",true);
		}
		var terminalBrandId = $("#terminalBrandId").val();
		if(terminalBrandId){
			loadTerminalModel();
		}
		getList();
	}
}

/**
 * 初始化单选框
 */
function initSelectRadio(){
	var selectedvalue = $("#selectedvalue").val();
	if(selectedvalue){
		$("#selectedvalue_"+selectedvalue).attr("checked",'checked'); 
		getRadio();
	}
}
/**
 * 初始化时间维度
 */
function initTimeSize(){
	var timeSizeId = $("#timeSizeId").val();
	if(timeSizeId){
		$("#"+timeSizeId).attr("checked",'checked'); 
	}
}
/**
 * 获得单选框
 */
function getRadio() {
	var selectedvalue = $("input[name='radio']:checked").val();
	if(selectedvalue==0){
		$("#serviceIPDiv").hide();
	}else{
		$("#serviceIPDiv").show();
	}
	for (var i = 0; i < 7; i++) {
		var tempId = '#radio_' + i;
		if (selectedvalue == i) {
			$(tempId).show();
		} else {
			$(tempId).hide();
		}
	}
}
/**
 * 页面校验
 */
function validatorParam(){
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	if(beginDate==null || beginDate==''){
		alert("请选择开始时间");
		return false;
	}
	if(endDate==null || endDate==''){
		alert("请选择结束时间");
		return false;
	}
	return true;
}
function getList() {
	delete d;
	var timeSize = $('input:radio[name="timeSize"]:checked').val();
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	// serverIP
	var serverIPBox = $('input:checkbox[name="serverIPBox"]:checked').val();
	var serverIP = $("#serverIP").val();
	// 维度
	var selectRadio = $('input:radio[name="radio"]:checked').val();
	var groupId = $("#groupId").val();
//	var groupName =$("#groupId").find("option:selected").text();
//	if(groupName=="全部")
//		groupName="";
	var userId = $("#userId").val();

	var terminalBrandId = $("#terminalBrandId").val();
	var terminalModelId = $("#terminalModelId").val();
	var apnId = $("#apnId").val();
	var sgw = $("#sgw").val();
	var cityCode = $("#area").val();
	var tac = $("#tac").val();
	var eNodeBID = $("#eNodeBID").val();
	var areaHouse = $("#areaHouse").val();

	if(validatorParam()){
		//$("#table tbody tr").remove();
		$("#tbodyId").remove();
		$('#table').append($("<tbody id='tbodyId'></tbody>"));
		if (datatable == undefined || datatable == "undefined" || datatable == null) {
		} else {
			datatable.fnDestroy();
		}
		// 构造页面显示列
		columns=[];
		columns = createColumns(serverIPBox, selectRadio);
		datatable = $('#table').dataTable({
			"bPaginate" : true, // 翻页功能
			"bLengthChange" : false, // 改变每页显示数据数量
			"bFilter" : false, // 过滤功能
			"bSort" : true, // 排序功能
			"bInfo" : true,// 页脚信息
			"bAutoWidth" : true,// 自动宽度
			// "sPaginationType": "full_numbers",//显示分页的样式 还有simple_numbers等
//			"sScrollX" : "100%",
			"iDisplayLength" : 50,
			"sScrollXInner" : "110%",
			"bScrollCollapse" : true,
			"oLanguage" : {
				"sLengthMenu" : "每页显示 _MENU_条",
				"sZeroRecords" : "没有找到符合条件的数据",
				"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
				"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
				"sInfoEmpty" : "没有记录",
				"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
				"sSearch" : "搜索：",
				"oPaginate" : {
					"sFirst" : "首页",
					"sPrevious" : "前一页",
					"sNext" : "后一页",
					"sLast" : "尾页"
				}
			},
			"bProcessing" : true,
			"bServerSide" : true,
			"sAjaxSource" : "../../businessAnalysis/tcp/infos",
			"fnServerData" : function(sSource, aoData, fnCallback) {
				delete params;
				var areaBoxStr="";
				$("input[name='areaBox']:checkbox").each(function() {
					if ($(this).attr("checked")) {
						areaBoxStr +=$(this).val()+"|";
					}
				});
				paras = {
						"aoData" : JSON.stringify(aoData),
						"timeSize" : timeSize,
						"beginDate" : beginDate,
						"endDate" : endDate,
						"serverIP" : serverIP,
						"selectRadio" : selectRadio,
						"groupId" : groupId,
						"userId" : userId,
						"terminalBrandId" : terminalBrandId,
						"terminalModelId" : terminalModelId,
						"apnId" : apnId,
						"sgw" : sgw,
						"cityCode" : cityCode,
						"tac" : tac,
						"eNodeBID" : eNodeBID,
						"areaHouse" : areaHouse,
						"serverIPBox":serverIPBox,
						"areaBoxStr":areaBoxStr
					};
				
				$.ajax({
					"type" : "post",
					"contentType" : "application/x-www-form-urlencoded",
					"url" : sSource,
					"dataType" : "json",
					"data" : paras, // 以json格式传递
					"success" : function(resp) {
						fnCallback(resp.pageDate);
						d = resp.allData;
					}
				});
			},
			columns : columns
			
		});
	}
}

/**
 * 构造页面显示的列
 * 
 * @param serverIPBox
 * @param selectRadio
 */
function createColumns(serverIPBox, selectRadio) {
	//导出的列
	exportColumns = [];
	var columns = [];
	var trObj = $('#trId');
	trObj.children().remove();
	//时间
	trObj.append($("<th>时间</th>"));
	columns.push({
		data : "report_date"
	});
	exportColumns.push({
		"key":"report_date",
		"name":"时间",
		"value":""
	});
	//根据页面条件显示
	// 显示服务IP
	if (serverIPBox == '0' && selectRadio != '0') {
		trObj.append($("<th >服务IP</th>"));
		columns.push({
			data : "server_ip"
		});
		exportColumns.push({
			"key":"server_ip",
			"name":"服务IP",
			"value":""
		});
	}
	// SWG
	if (selectRadio == '4') {
		trObj.append($("<th >SGW</th>"));
		columns.push({
			data : "sgw_name",
			render : function(value, type, row) {
				if (value == null || value == "") {
					value = "-";
				}
				return value;
			}
		});
		
		exportColumns.push({
			"key":"sgw_name",
			"name":"SGW",
			"value":""
		});
	} else if (selectRadio == '5') {// 区域
		// 城市
		trObj.append($("<th >地市</th>"));
		columns.push({
			data : "city_code",
			render : function(value, type, row) {
				if(value==null || value==''){
					value = " ";
				}
				return value;
			}
		});
		exportColumns.push({
			"key":"city_code",
			"name":"地市",
			"value":""
		});
		// 处理areaBox多选框
		$("input[name='areaBox']:checkbox")
				.each(
						function() {
							if ($(this).attr("checked")) {
								var areatBoxId = $(this).val();
								if (areatBoxId == '0') {// TAC
									trObj.append($("<th >TAC</th>"));
									columns.push({
										data : "tac"
									});
									exportColumns.push({
										"key":"tac",
										"name":"TAC",
										"value":""
									});
								} else if (areatBoxId == '1') {// eNodeBID
									trObj.append($("<th >eNodeBID</th>"));
									columns.push({
										data : "enodebid"
									});
									exportColumns.push({
										"key":"enodebid",
										"name":"eNodeBID",
										"value":""
									});
								} else if (areatBoxId == '2') {// 小区
									trObj.append($("<th >小区</th>"));
									columns.push({
										data : "cell_name",
										render : function(value, type, row) {
											var cellName="";
											if(value){
												cellName = value;
											}
											return cellName;
										}
									});
									exportColumns.push({
										"key":"cell_name",
										"name":"小区",
										"value":""
									});
								}
							}
						});
	} else if (selectRadio == '0') {// 用户组
		trObj.append($("<th >用户组</th>"));
		columns.push({
			data : "group_name",
			render : function(value, type, row) {
				if(value==null){
					value="";
				}
				return value;
			}
		
		});
		exportColumns.push({
			"key":"group_name",
			"name":"用户组",
			"value" :""
		});
	} else if (selectRadio == '1') {// 用户
		trObj.append($("<th >MSISDN</th>"));
		columns.push({
			data : "msisdn"
		});
		exportColumns.push({
			"key":"msisdn",
			"name":"MSISDN",
			"value":""
		});
		trObj.append($("<th >IMSI</th>"));
		columns.push({
			data : "imsi"
		});
		exportColumns.push({
			"key":"imsi",
			"name":"IMSI",
			"value":""
		});
	} else if (selectRadio == '2') {// 终端
		trObj.append($("<th >终端类型</th>"));
		var terminalBrandName="";
		columns.push({
			data : "terminal_brand",
//			render : function(value, type, row) {
//				if (value == null || value == "") {
//					value = " ";
//				}
//				return value;
//			}
			render : function(value, type, row) {
				$("#terminalBrandId option").each(function() {
					if ($(this).val() == value) {
						terminalBrandName = $(this).text();
					}
				});
				return terminalBrandName;
			}
		});
		exportColumns.push({
			"key":"terminal_brand",
			"name":"终端类型",
			"value":""
		});
		
		var terminalModelName="";
		trObj.append($("<th >终端型号</th>"));
		columns.push({
			data : "terminal_model",
			render : function(value, type, row) {
				if (value == null || value == "") {
					value = " ";
				}
				return value;
//			render : function(value, type, row) {
//				$("#terminalModelId option").each(function() {
//					if ($(this).val() == value) {
//						terminalModelName = $(this).text();
//					}
//				});
//				return terminalModelName;
			}
		});
		exportColumns.push({
			"key":"terminal_model",
			"name":"终端型号",
			"value":""
		});
	} else if (selectRadio == '3') {// apn
		trObj.append($("<th >APN</th>"));
		columns.push({
			data : "apn_name"
		});
		exportColumns.push({
			"key":"apn_name",
			"name":"APN",
			"value":""
		});
	}else if (selectRadio == '6') {
		//SP
		trObj.append($("<th >SP</th>"));
		columns.push({
			data : "sp"
		});
		exportColumns.push({
			"key" : "sp",
			"name" : "SP",
			"value" : ""
		});
		// site
		if ($('#site').val() != '') {// 网站
			alert($('#site').val());
			trObj.append($("<th >网站</th>"));
			columns.push({
				data : "web_site"
			});
			exportColumns.push({
				"key" : "web_site",
				"name" : "网站",
				"value" : ""
			});
		}
	}
	
	//TCP握手总次数
	trObj.append($("<th>TCP握手总次数</th>"));
	columns.push({
		data : "tcp_total_number",
		render : function(value, type, row) {
			if (value == null || value == "") {
				value = "0";
			}
			return value;
		}
	});
	exportColumns.push({
		"key":"tcp_total_number",
		"name":"TCP握手总次数",
		"value":""
	});
	//握手失败次数
	trObj.append($("<th>握手失败次数</th>"));
	columns.push({
		data : "tcp_fail_number",
		render : function(value, type, row) {
			if (value == null || value == "") {
				value = 0;
			}
			return value;
		}
	});
	exportColumns.push({
		"key":"tcp_fail_number",
		"name":"握手失败次数",
		"value":""
	});
	//握手成功率
	trObj.append($("<th>握手成功率(%)</th>"));
	columns.push({
		data : "tcp_success_rate",
		render : function(value, type, row) {
			if (value == null || value == "") {
				value = 0;
			}
			return value;
		}
	});
	exportColumns.push({
		"key":"tcp_success_rate",
		"name":"握手成功率",
		"value":""
	});
	//握手时延
	trObj.append($("<th>握手时延</th>"));
	columns.push({
		data : "tcp_delay_time_avg",
		render : function(value, type, row) {
			if (value == null || value == "") {
				value = 0;
			}
			return value;
		}
	});
	exportColumns.push({
		"key":"tcp_delay_time_avg",
		"name":"握手时延",
		"value":""
	});
	//上行重传率(%)
	trObj.append($("<th>上行重传率(%)</th>"));
	columns.push({
		data : "re_upload_rate_up",
		render : function(value, type, row) {
			if (value == null || value == "") {
				value = 0;
			}
			return value;
		}
	});
	exportColumns.push({
		"key":"re_upload_rate_up",
		"name":"上行重传率(%)",
		"value":""
	});
	//下行重传率(%)
	trObj.append($("<th>下行重传率(%)</th>"));
	columns.push({
		data : "re_upload_rate_down",
		render : function(value, type, row) {
			if (value == null || value == "") {
				value = 0;
			}
			return value;
		}
	});
	exportColumns.push({
		"key":"re_upload_rate_down",
		"name":"下行重传率(%)",
		"value":""
	});
	//上行乱序率(%)
	trObj.append($("<th>上行乱序率(%)</th>"));
	columns.push({
		data : "not_in_order_rate_up",
		render : function(value, type, row) {
			if (value == null || value == "") {
				value = 0;
			}
			return value;
		}
	});
	exportColumns.push({
		"key":"not_in_order_rate_up",
		"name":"上行乱序率(%)",
		"value":""
	});
	//下行乱序率(%)
	trObj.append($("<th>下行乱序率(%)</th>"));
	columns.push({
		data : "not_in_order_rate_down",
		render : function(value, type, row) {
			if (value == null || value == "") {
				value = 0;
			}
			return value;
		}
	});
	exportColumns.push({
		"key":"not_in_order_rate_down",
		"name":"下行乱序率(%)",
		"value":""
	});
	//碎片率(%)
	trObj.append($("<th>碎片率(%)</th>"));
	columns.push({
		data : "fragment_rate",
		render : function(value, type, row) {
			if (value == null || value == "") {
				value = 0;
			}
			return value;
		}
	});
	exportColumns.push({
		"key":"fragment_rate",
		"name":"碎片率(%)",
		"value":""
	});
	return columns;
}

function resetQueryForm() {
	$('#queryForm')[0].reset();
	getRadio();
}

function exportExcel() {
	if (d) {
		paras['exportColumns'] = JSON.stringify(exportColumns);
		$.ajax({
			type : "POST",
			url : "../../businessAnalysis/tcp/exportBigDataExcel?rand="
					+ Math.random(),
			dataType : "json",
			"data" : paras,
			success : function(data) {
				if (data.flag) {
					var url = "../../businessAnalysis/attachment/downFiles?path="
							+ data.path;
					window.location.href = url;
				} else {
					alert(data.msgs);
				}
			}
		});
	} else {
		alert("请先查询数据！");
	}
}

/*// 下拉树 begin
function onClick(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"), nodes = zTree
			.getSelectedNodes(), v = "";
	nodes.sort(function compare(a, b) {
		return a.id - b.id;
	});
	for (var i = 0, l = nodes.length; i < l; i++) {
		v += nodes[i].name + ",";
	}
	if (v.length > 0)
		v = v.substring(0, v.length - 1);
	var cityObj = $("#citySel");
	cityObj.attr("value", v);
	$("#area").val(treeNode.id);

	hideMenu();
}
*//**
 * 显示树
 *//*
function showMenu() {
	var cityObj = $("#citySel");
	var cityOffset = $("#citySel").offset();
	$("#menuContent").css({
		left : cityOffset.left - 26 + "px",
		top : cityOffset.top - 206 + "px"
	}).slideDown("fast");

	$("body").bind("mousedown", onBodyDown);
}
*//**
 * 隐藏树
 *//*
function hideMenu() {
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(
			event.target).parents("#menuContent").length > 0)) {
		hideMenu();
	}
}*/